package com.ukefu.util.client;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Set;

import com.corundumstudio.socketio.SocketIOClient;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.Multimap;
import com.ukefu.util.UKTools;

public abstract class NettyClient {
	
	protected Multimap<String, SocketIOClient> clientsMap = HashMultimap.create();
	
	public int size() {
		return clientsMap.size() ;
	}
	
	public Collection<SocketIOClient> getClients(String key){
		return clientsMap.get(key) ;
	}
	
	public Collection<SocketIOClient> getClients() {
		return clientsMap.values() ;
	}
	
	public void putClient(String key , SocketIOClient client) {
		clientsMap.put(key, client) ;
	}
	
	public void clean() {
		List<String> keys = new ArrayList<String>();
		Set<String>  keyValues = clientsMap.keySet() ;
		if(keyValues!=null && keyValues.size() > 0) {
			keys.addAll(keyValues) ;
		}
		for(String key : keys) {
			List<SocketIOClient> clients = new ArrayList<SocketIOClient>();
			if(this.getClients(key)!=null && this.getClients(key)!=null) {
				clients.addAll(this.getClients(key));
				for(SocketIOClient client : clients) {
					if(!client.isChannelOpen()) {
						client.disconnect();
						clientsMap.remove(key, client) ;
					}
				}
			}
		}
	}
	
	public void removeClient(String key , String id) {
		Collection<SocketIOClient> values = this.getClients(key) ;
		if(values!=null && values.size() > 0) {
			List<SocketIOClient> keyClients = new ArrayList<SocketIOClient>();
			keyClients.addAll(values) ;
			for(int i=0 ; i<keyClients.size() ; i++){
				SocketIOClient client = keyClients.get(i) ;
				if(client!=null) {
					if(UKTools.getContextID(client.getSessionId().toString()).equals(id)){
						clientsMap.remove(key, client) ;
					}
					client.disconnect();
					clientsMap.remove(key, client) ;
				}
			}
		}
	}
}
